//
//  CZUserAccountViewModel.swift
//  weibo
//
//  Created by Mac on 16/5/15.
//  Copyright © 2016年 fengzhixiang. All rights reserved.
//

import UIKit

class CZUserAccountViewModel: NSObject {

    //单例
    static let shareInstanse: CZUserAccountViewModel = CZUserAccountViewModel()

    //账号归档和解档的路径
    let userAccountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/account.plist"

    ///账号,全局只要拿到单例就可以访问
    var userAccount: CZUserAccount?

    ///用户是否登录
    var isUserLogin: Bool {
        get{
            return userAccount != nil// 账号!=nil就表示登录了

        }

    }

    override init() {
        super.init()
        //加载沙盒里面的账号,赋值给userAccount, 只需要加载一次
        userAccount = loadUserAccount()
    }

    ///发送POST请求AccountToken
    func loadAccountToken(code: String,callback: (error: NSError?)->()){


        // 发送POST请求获取AccessToken
        let urlString = "oauth2/access_token"
        //参数
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : redirect_uri
        ]
        // 如果已经授权成功消息在授权的时候不会再看到这个界面,相当于新浪会自动帮我们点击授权按钮
        CZNetworkTool.sharedInstance.requset(RequestMethod.POST, URLString: urlString, parameters: parameters, progress: nil, success: { (task, responseObject) -> Void in
            CZPrint(items: "获取AccessToken成功: \(responseObject)")

            //判断返回的数据是否能够转成字符串
            if let result = responseObject as?[String: AnyObject]{
                //字典转模型
                let userAccount = CZUserAccount(dict: result)
                CZPrint(items: "userAccount: \(userAccount)")
                //调用归档的方法,将模型归档到沙盒里面
                let userAccoutPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/account.plist"
                CZPrint(items: "userAccoutPath: \(userAccoutPath)")
                NSKeyedArchiver.archiveRootObject(userAccount, toFile: userAccoutPath)
                //告诉控制器,模型保存好了
                callback(error: nil)
            }else{
                CZPrint(items: "返回数据转字典失败了")
            }

            }, failure: { (task, error) -> Void in
                callback(error: error)

        })

    }

    //解档账号
    func loadUserAccount() -> CZUserAccount? {
        //解档对象
       if let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(self.userAccountPath) as? CZUserAccount{
        if userAccount.expiresDate?.compare(NSDate()) != NSComparisonResult.OrderedAscending {
            //没有过期
            CZPrint(items: "没有过期")
            return userAccount
            } else {
                return nil
            }
       } else {
        //没有加载出账号
        return nil
        }


    }


}



